$(function() {
    var webSite = "http://api.hexfuture.com";
    var reg1 = new RegExp(name+"exercisePoolId([\\S]+?)");
    var para=window.location.pathname.substr(1).match(reg1);
    
    var exercisePoolId = getUrlParam("exercisePoolId");
    var echapterid = getUrlParam("echapterid");
    var echapterName=decodeURI(getUrlParam("eChapterName"));
    
    template.helper('urlFormat', function(date, format) {

        //  var date = { size: 2, value: format + "|" + date,level:'L' };
        //  return qr.toDataURL(date);
        return "/create_qrcode?text=" + format + "|" + date + "&size=" + 2;
    });

    template.helper('abcFormat', function(date, format) {
        var a = ['A.','B.','C.','D.','E.','F.','G.','H.','I.','G.','K.','L.','M.','N.','O.','P.','Q.','R.','S.','T.','U.','V.','W.','X.','Y.','Z.'];
        return a[date];
    });
    // template.helper('choiceAnswerFormat', function(date, format) {
    //     for (i = 0; i < format.length; i++) {
    //         if (format[i] == "1") {
    //             return date[i];
    //         }
    //     }

    // });
    function getUrlParam(name) {
        var reg = new RegExp(name+"=([a-zA-Z\%\\d]+[^&]?)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.pathname.substr(1).match(reg);  //匹配目标参数
        if (r != null) return r[0].split("=")[1]; return null; //返回参数值
    }
    function Init(params) {
        /*return $.ajax({
            type: "get",
            dataType: "json",//4295865427
            url: webSite + "/ExerciseContents/SearchEChapters?exercisePoolId=" + exercisePoolId + "&ssotoken=Jiyuan",
            //data: "id=" + id,
            //complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示
            success: function(data) {
                var html = template('eChapterlist', data);
                $("#content").html(html);
                IniteChapterHte();
            }
        })*/
        var html='<div class="hex_eChapterName">'+echapterName+'</div><div hex_echapter="'+echapterid+'" class="hex_eChapter">'+echapterName+'</div>';
        $("#content").html(html);
        IniteChapterHte();
    }
    function IniteChapterHte(params) {
        /*$(".hex_eChapter").each(function() {
            var eKey = $(this).attr("hex_eChapter");

            $.ajax({
                type: "get",
                dataType: "json",//4295865427
                url: webSite + "/ExerciseContents/SearchHTEByEChapter?eChapterId=" + eKey + "&ssotoken=Jiyuan",
                //data: "id=" + id,
                //complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示
                success: function(data) {
                    var html = template('eChapterHtelist', data);
                    $("[hex_eChapter='" + eKey + "']").first().html(html);
                    InitHteExercise();
                }
            })
        })*/
        $.ajax({
                type: "get",
                dataType: "json",//4295865427
                url: webSite + "/ExerciseContents/SearchHTEByEChapter?eChapterId=" + echapterid + "&ssotoken=Jiyuan",
                //data: "id=" + id,
                //complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示
                success: function(data) {
                    var html = template('eChapterHtelist', data);
                    $("[hex_eChapter='" + echapterid + "']").first().html(html);
                    InitHteExercise();
                }
            })
    }
    function InitHte(params) {
        return $.ajax({
            type: "get",
            dataType: "json",//4295865427
            url: webSite + "/ExercisePoolHTEQuery/GetExercisePoolHTEByEPoolId/" + exercisePoolId + "?startPage="+startPage+"&ssotoken=Jiyuan",
            //data: "id=" + id,
            //complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示
            success: function(data) {
                var html = template('htelist', data);
                $("#content").html(html);
                InitHteExercise();
            }
        })
    }
    function InitHteExercise() {
        $(".hex_hte").each(function() {
            var eKey = $(this).attr("hex_hteid");
            GetHteExercise(eKey);
        })

    }
    function GetHteExercise(hteid) {
        Loading();
        return $.ajax({
            type: "get",
            dataType: "json",
            url: webSite + "/HTEModel/" + hteid + "?ssotoken=Jiyuan",
            //data: "id=" + id,
            //complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示
            success: function(data) {
                var html = template('exerciselist', data);
                $("[hex_hteid='" + hteid + "']").first().html(html);
                InitExercise(hteid);
                 LoadingEnd();
            }
        })
    }
    function InitExercise(hteid) {
        var exNum=$("[hex_hteid='" + hteid + "'] .hex_exercise").length;
        //如果题的数量大于6，则不异步请求
        var isAsync=true;
        if(exNum>6){
            isAsync=false;
        }
        $("[hex_hteid='" + hteid + "'] .hex_exercise").each(function() {
            var eKey = $(this).attr("hex_exerciseid");
            var isSuccess= GetExercise(eKey, hteid,isAsync);
        });
    }
    function GetExercise(eid, hteid,isAsync) {
        var isSuccess=false;
         $.ajax({
            type: "get",
            dataType: "json",
            async:isAsync,
            url: webSite + "/Exercises/Get/" + eid + "?ssotoken=Jiyuan",
            //data: "id=" + id,
            //complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示
            success: function(data) {
                var source;
                if (data.ET == "FillBlank") {
                    source = template('fillblankExercise', data);
                }
                else if (data.ET == "Judgment") {
                    source = template('JudgmentExercise', data);
                }
                else if (data.ET == "Subjective") {
                    source = template('SubjectiveExercise', data);
                }
                else if (data.ET == "Program") {
                    source = template('ProgramExercise', data);
                }
                else if (data.ET == "ChoiceFillBlank") {
                    source = template('ChoiceFillBlankExercise', data);
                }
                else if (data.ET == "Compute") {
                    source = template('ComputeExercise', data);
                }
                else {
                    source = template('choiceExercise', data);
                }
                $("[hex_hteid='" + hteid + "'] [hex_exerciseid='" + eid + "']").first().html(source);
                isSuccess=true;
            }
        })
        return isSuccess;
    }
    Init();
    function convertImagesToBase64() {
        contentDocument = document.getElementById("content");
        var regularImages = contentDocument.querySelectorAll("img");
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        [].forEach.call(regularImages, function(imgElement) {

            // var dataURL;
            // try {
            //     ctx.clearRect(0, 0, canvas.width, canvas.height);
            //     canvas.width = imgElement.width;
            //     canvas.height = imgElement.height;
            //     ctx.drawImage(imgElement, 0, 0);
            //     dataURL = canvas.toDataURL();
            // } catch (err) {
            //     // document.writeln("Error name: " + err.name + "");
            //     // document.writeln("Error message: " + err.message);
            //     console.log(imgElement);
            // }
            // finally {
            //     imgElement.setAttribute('src', dataURL);
            // }

            ctx.clearRect(0, 0, canvas.width, canvas.height);
            canvas.width = imgElement.width;
            canvas.height = imgElement.height;
            ctx.drawImage(imgElement, 0, 0);
            var dataURL = canvas.toDataURL();
            imgElement.setAttribute('src', dataURL);
        })
        canvas.remove();
    }
    function GetDocx() {
        // var time = Date.now();
        // console.log(time);
        // $.post("/test", { html: $("#content").html(), time: time }, function (data) {
        //     //console.log("回来了" + data);
        // });
        // var html = "<a href='/docx/" + time + ".docx'>点击下载</a>";
        // $("#url").html(html);

        convertImagesToBase64();
        var content = $("#content").html();

        //console.log(content);
        $("#hidden_html").val(content);
        $("#url").show();

    }



    //前提：所有ajax请求都是用jquery的$.ajax发起的，而非原生的XHR；
    var ajaxBack = $.ajax;
    var ajaxCount = 0;
    var allAjaxDone = function() {
        // $.post("/test",{html:$("#content").html()},function(date){
        //     alert(date);
        // });
        //GetDocx();
    } //一行代码，就可以知道所有ajax请求什么时候结束
    //由于get/post/getJSON等，最后还是调用到ajax，因此只要改ajax函数即可
    $.ajax = function(setting) {
        ajaxCount++;
        var cb = setting.complete;
        setting.complete = function() {
            if ($.isFunction(cb)) { cb.apply(setting.context, arguments); }
            ajaxCount--;
            $("#state").text(ajaxCount);
            if (ajaxCount == 0 && $.isFunction(allAjaxDone)) {
                allAjaxDone();
            }
        }
        ajaxBack(setting);
    }


})